from celery import shared_task
from django.utils import timezone
from django.db.models import Count
from cryptography.fernet import Fernet
from django.conf import settings
import secrets
import string
from .models import Host, City, IDC, HostStatistic

# 初始化加密器（需在settings配置FERNET_KEY）
cipher_suite = Fernet(settings.FERNET_KEY)


def generate_random_password(length=12):
    """生成随机密码（包含大小写、数字、特殊字符）"""
    chars = string.ascii_letters + string.digits + '!@#$%^&*()'
    return ''.join(secrets.choice(chars) for _ in range(length))


def encrypt_password(password):
    """加密密码"""
    return cipher_suite.encrypt(password.encode()).decode()


@shared_task
def rotate_root_passwords():
    """每8小时轮换所有主机root密码"""
    for host in Host.objects.all():
        new_pwd = generate_random_password()
        host.root_password = encrypt_password(new_pwd)
        host.save()
    return f"已更新{Host.objects.count()}台主机密码"


@shared_task
def statistic_host_count():
    """每天0点按城市和机房统计主机数量"""
    today = timezone.now().date()
    # 按城市+机房分组统计
    stats = Host.objects.values("idc__city", "idc").annotate(count=Count("id"))

    for stat in stats:
        HostStatistic.objects.update_or_create(
            city_id=stat["idc__city"],
            idc_id=stat["idc"],
            date=today,
            defaults={"count": stat["count"]}
        )
    return f"已完成{len(stats)}条统计记录"